import React, { Component } from 'react';

import { Row, Col, Table, Button, Icon, Tabs, Modal, Steps, Tag, message, Tooltip } from 'antd';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BannerAnim, { Element,Arrow } from 'rc-banner-anim';
import TweenOne from 'rc-tween-one';
import IframeComm from "../../components/IframeComm";
import 'rc-banner-anim/assets/index.css';
import styles from "./style.less";
import Link from 'umi/link';
import axios from 'axios';
import Api from '../../services/apis';
import ReactEcharts from 'echarts-for-react';


const BgElement = Element.BgElement;
const TabPane = Tabs.TabPane;

const nopic = require('../../assets/nopic.png');
const Step = Steps.Step;

const data = [
  {
    key: '1',
    name: '国税局住宅',
    company: '国税局',
    project: '国税局划转房产',
    startTime: '2018年12月12日',
    endTime: '2018年12月12日',
    operator: '邓美楠',
    state: '办理中',
    type: '使用权证',
    nature: '房屋',
    charge: '**代办公司',
    ascription: '国税局',
    transferStatus: '未过户',
    projectCode: '',
    pageSize: 5,
    current:1,
    _current:1,
  },
];


@connect(({ user, project, activities, chart, loading }) => ({
  currentUser: user.currentUser,
  currentUserLoading: loading.effects['user/fetchCurrent']
}))
class BuildingDetails extends Component {
  constructor(props) {
    super(props);
    this.state = {
      doc: 1,
      headerData: [
        {
          tit: '交通',
          icon: 'environment',
          choiced: true
        },
        {
          tit: '学校',
          icon: 'team',
          choiced: false
        },
        {
          tit: '购物',
          icon: 'shopping-cart',
          choiced: false
        },
        {
          tit: '医院',
          icon: 'schedule',
          choiced: false
        },
        {
          tit: '银行',
          icon: 'bank',
          choiced: false
        },
        {
          tit: '体育休闲',
          icon: 'dribbble',
          choiced: false
        },
        {
          tit: '景观',
          icon: 'cloud',
          choiced: false
        },
        {
          tit: '加油站',
          icon: 'thunderbolt',
          choiced: false
        },
      ],
      choicedIndex: 0,
      step: {
        doc: {},
        itemList: []
      },
      stepCount: 0,
      postMsg: {},
      feesData: [
        {
          title: '水费',
          money: '-',
          icon: 'dashboard'
        },
        {
          title: '电费',
          money: '-',
          icon: 'thunderbolt'
        },
        {
          title: '供暖费',
          money: '-',
          icon: 'sliders'
        },
        {
          title: '物业费',
          money: '-',
          icon: 'money-collect'
        },
        {
          title: '燃气费',
          money: '-',
          icon: 'fire'
        },
      ],
      buildingData: [],
      modalVisible: false,
      buildingInfo: new Object,
      pageSize: 5,
      current: 1,
      _current: 1,
      _pageSize: 5,
      chartData:  {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: ['电费', '水费', '燃气费', '供暖费', '物业费', '维修费']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: []
        },
        yAxis: {
            type: 'value',
            boundaryGap: [0, 0.01]
        },
        series:  [
          {
              name: '电费',
              type: 'bar',
              data: []
          },
          {
              name: '水费',
              type: 'bar',
              data: []
          },
          {
              name: '燃气费',
              type: 'bar',
              data: []
          },
          {
              name: '供暖费',
              type: 'bar',
              data: []
          },
          {
              name: '物业费',
              type: 'bar',
              data: []
          },
          {
              name: '维修费',
              type: 'bar',
              data: []
          }
        ]
      },
      rentalData: [],
    };
  }

  //获取能耗统计
  getStatisticMoney = (buildingCode) => {
    const that = this;
    axios.post(Api.amStatisticMoney, {
      building_code: buildingCode
    }).then(function (resp) {
      const data= eval('['+resp.data+']')[0].data;
      let chartData = JSON.parse(JSON.stringify(that.state.chartData));

      for(var i in data){
        chartData.xAxis.data.push(i + "月");
        chartData.series[0].data.push(data[i].energyFee); //电费
        chartData.series[1].data.push(data[i].waterFee); //水费
        chartData.series[2].data.push(data[i].gasFee); //燃气费
        chartData.series[3].data.push(data[i].heatingFee); //供暖费
        chartData.series[4].data.push(data[i].propertyFee); //物业费
        chartData.series[5].data.push(data[i].maintainFee); //维修费
      };
      that.setState({
        chartData: chartData
      })
    });
  }

  changeList(index) {
    let headerData = this.state.headerData;
    headerData[this.state.choicedIndex].choiced = false;
    headerData[index].choiced = true;
    this.setState({
      headerData,
      choicedIndex: index,
    });
  }


  sendData = (buildingCode) => {
    const that = this;
    this.setState({ loading: true })
    axios.post(Api.amGetProInfo, {
        projectCode: buildingCode
    }).then(function (resp) {
        const { data } = resp;
        if (data.buildList && data.buildList.length !== 0) {
            data.buildList.forEach((item, index) => {
                item.key = index;
            })
        }
        that.setState({
            projectName: data.projectName,
            projectCode: data.projectCode,
            coveredArea: data.coveredArea,
            buildCount: data.buildCount,
            houseCount: data.houseCount,
            plotRatio: data.plotRatio,
            transferUnit: data.transferUnit,
            assetStatus: data.assetStatus,
            buildList: data.buildList,
        })
        that.setState({ loading: false })
    })
  }
  
  pageChange = page => {
    this.setState({current: page},() => {
        this.getBuildHouseInfo();
      }
    );
  };

  pageChange2 = page => {
    this.setState({_current: page},() => {
        this.getHouseLeaseInfo();
      }
    );
  };

  componentWillMount() {
    const buildingCode = this.props.location.query.buildingCode ? this.props.location.query.buildingCode : this.props.location.state.buildingCode;

    this.setState({
      buildingCode: buildingCode,
    }, () => {
      this.getBuildHouseInfo();
    });
    this.getBuildingInfo(buildingCode);
    this.getHouseLeaseInfo(buildingCode);
    //获取能耗统计
    this.getStatisticMoney(buildingCode);
  }

  getHouseLeaseInfo = (buildingCode) => {
    const that = this;
    axios.post(Api.getHouseLeaseInfo, {
      buildingCode: buildingCode,
      currentPage: that.state._current,
      pageSize: 5
    }).then((res) => {
      const { data } = res;
      data.list.forEach((item, i) => {
        item.key = i;
      })
      that.setState({
        rentalData: data.list,
        _current: that.state._current,
        _total: data.totalSize
      })
    });
  }
  
  getBuildingInfo(buildingCode) {
    const that = this;
    //基本信息
    axios.all([
      this.getSysDic("OWNER_SHIP_STATUS"),
      this.getSysDic("OWNER_SHIP_TYPE"),
      this.getSysDic("ASSET_STATUS"),
      this.getBuildInfo({ buildingCode }),
    ])
      .then(axios.spread(function (r1, r2, r3, r4) {
        const ownerStatus = r1.data; //权属状态
        const ownerType = r2.data;  //权属形式
        const assetStatus = r3.data;  //资产状态
        const buildingInfo = r4.data;  //基本信息

        if (buildingInfo.assetStatus) {
          const result = assetStatus.find(item => item.dicId == buildingInfo.assetStatus);
          buildingInfo.assetStatusText = result > 0 ? result.dicName : '';
        }

        if (buildingInfo.ownerType) {
          const result = ownerType.find(item => item.dicId == buildingInfo.ownerType);
          buildingInfo.ownerTypeText = result > 0 ? result.dicName : '';
        }

        if (buildingInfo.ownerStatus) {
          const result = ownerStatus.find(item => item.dicId == buildingInfo.ownerStatus);
          buildingInfo.ownerStatusText = result > 0 ? result.dicName : '';
        }
        
        if (!buildingInfo.images || !Array.isArray(buildingInfo.images)) {
          buildingInfo.images = [];
        }
        
        that.setState({
          buildingInfo: buildingInfo
        });
        axios.get(Api.getBuildingOwnership, {
          params: {
            buildingCode: buildingCode
          }
        }).then((res) => {
          if (Number(res.data.doc) === 0) {
            that.setState({
              doc: Number(res.data.doc)
            });
          } else {
            that.setState({
              step: res.data,
              stepCount: res.data.itemList.length
            });
          };
        });

        //楼栋详情
        axios.get(Api.getBuildingMessage, {
          params: {
            buildingCode: buildingCode
          }
        }).then((res) => {
          let feesData = that.state.feesData;
          feesData[0].money = res.data.fee.waterFee;
          feesData[1].money = res.data.fee.electricFee;
          feesData[2].money = res.data.fee.heatingFee;
          feesData[3].money = res.data.fee.propertyFee;
          feesData[4].money = res.data.fee.gasFee;
          that.setState({
            feesData,
            postMsg: res.data
          });
        });

      }));
  }

  //获取房屋列表
  getBuildHouseInfo = () => {
    const that = this;
    axios.get(Api.getBuildHouseInfo, {
      params: {
        offset: that.state.current,
        buildingCode: that.state.buildingCode
      }
    }).then((res) => {
      const { data } = res;
      data.list.forEach((item, i) => {
        item.key = i;
      })
      that.setState({
        buildingData: data.list,
        current: parseInt(data.currentPage),
        total: data.totalSize
      })
    });
  }
  
  //获取基本信息
  getBuildInfo = (buildingCode) => {
    return axios.post(Api.amGetBuildInfo, { ...buildingCode })
  }

  //获取系统参数
  getSysDic = (type) => {
    return axios.post(Api.amGetSysDic, { key: type })
  }

  setModalVisible(modalVisible, ) {
    if (this.state.doc === 0) {
      message.warn('暂无数据！')
    } else {
      this.setState({ modalVisible });
    }
  }
  
  render() {
    const that = this;
    const {
      currentUserLoading,
    } = this.props;

    const buildingInfo = this.state.buildingInfo;
    const columns = [
      {
          title: '划转单位',
          dataIndex: 'transferUnit',
          key: 'transferUnit',
      },
      {
          title: '详细地址',
          dataIndex: 'location',
          key: 'location',
      },
      {
          title: '栋号',
          dataIndex: 'buildingNum',
          key: 'buildingNum',
      },
      {
          title: '楼层',
          dataIndex: 'currentFloor',
          key: 'currentFloor',
      },
      {
          title: '房号',
          key: 'houseName2',
          dataIndex: 'houseName2',
      },
      {
          title: '使用面积',
          key: 'useArea',
          dataIndex: 'useArea',
      },
      {
          title: '住房用途',
          key: 'houseAction',
          dataIndex: 'houseAction',
      },
      {
          title: '容纳人数',
          key: 'houseMeetingroomPersons',
          dataIndex: 'houseMeetingroomPersons',
      },
      {
          title: '房型',
          key: 'houseTpye',
          dataIndex: 'houseTpye',
      },
      {
          title: '住房性质',
          key: 'houseProperty',
          dataIndex: 'houseProperty',
      },
      
  ];

    const columns2 = [
    {
        title: '划转单位',
        dataIndex: 'org_name',
        key: 'org_name',
    },
    {
        title: '详细地址',
        key: 'address',
        dataIndex: 'address',
    },
    {
        title: '出租方（甲方）',
        dataIndex: 'party_a',
        key: 'party_a',
    },
    {
        title: '承租方（乙方）',
        key: 'party_b',
        dataIndex: 'party_b',
    },
    {
        title: '出租面积',
        key: 'lease_harea',
        dataIndex: 'lease_harea',
    },
    {
        title: '单价',
        key: 'houseleasedprice',
        dataIndex: 'houseleasedprice',
    },
    {
        title: '总金额',
        key: 'rent_all',
        dataIndex: 'rent_all',
    },
  ];

    return (
      <PageHeaderWrapper
        loading={currentUserLoading}
      >
        <div className={`${styles.cdMain} ${styles.buildingMain}`}>
          <Row>
            <div className={`${styles.cdHeaderLeft} pull-left`}>
              <BannerAnim prefixCls='buildingDetailsBannerItem' autoPlay>
                {
                  buildingInfo.images && buildingInfo.images.map((item, index) =>
                      <Element
                        key={index}
                      >
                        <BgElement
                          key='bg'
                          className={styles.bannerItemPic}
                          style={{
                            backgroundImage: `url(http://192.168.50.55:55555/res_file${item.filePath})`
                          }}
                        />
                      </Element>
                    )
                }
              </BannerAnim>
            </div>
            <div className={`${styles.cdHeaderRight} pull-left`}>
              <h1>
                资产信息
              </h1>
               {/*buildingInfo.projectCode !== 'PJ008' ?*/
                <Row>
                  <Col span={12} title={buildingInfo.buildingName2}>
                    <span className='label'>楼宇名称：</span>{buildingInfo.buildingName2 ? buildingInfo.buildingName2 : '-'}
                  </Col>
                  <Col span={12} title={buildingInfo.buildingCode}>
                    <span className='label'>楼宇编号：</span>{buildingInfo.buildingCode ? buildingInfo.buildingCode : '-'}
                  </Col>
                  <Col span={12} title={buildingInfo.manageType}>
                    <span className='label'>管理方式：</span>{buildingInfo.manageType ? buildingInfo.manageType : '-'}
                  </Col>
                  <Col span={12} title={buildingInfo.assetStatusText}>
                    <span className='label'>资产状态：</span>{buildingInfo.assetStatusText ? buildingInfo.assetStatusText : '-'}
                  </Col>
                  <Col span={12} title={buildingInfo.use}>
                    <span className='label'>用途：</span>{buildingInfo.use ? buildingInfo.use : '-'}
                  </Col>
                  <Col span={12} title={buildingInfo.receivedDate}>
                    <span className='label'>接管日期：</span>{buildingInfo.receivedDate ? buildingInfo.receivedDate : '-'}
                  </Col>
                  <Col span={12} title={buildingInfo.ownerTypeText}>
                    <span className='label'>权属形式：</span>{buildingInfo.ownerTypeText ? buildingInfo.ownerTypeText : '-'}
                  </Col>
                  <Col span={12}>
                    <span className='label'>权属状态：</span>{buildingInfo.ownerStatusText ? buildingInfo.ownerStatusText : '-'}
                  </Col>
                  <Col span={12} title={buildingInfo.buildingStructure}>
                    <span className='label'>建筑结构：</span>{buildingInfo.buildingStructure ? buildingInfo.buildingStructure : '-'}
                  </Col>
                  <Col span={12} title={buildingInfo.totalFloor}>
                    <span className='label'>总层数：</span>{buildingInfo.totalFloor ? buildingInfo.totalFloor : '0'}
                  </Col>
                  <Col span={12} title={buildingInfo.houseCount}>
                    <span className='label'>房间数：</span>{buildingInfo.houseCount ? buildingInfo.houseCount : '-'}
                  </Col>
                  <Col span={12} title={buildingInfo.plotRatio}>
                    <span className='label'>容积率：</span>{buildingInfo.plotRatio ? (buildingInfo.plotRatio).toFixed(2) : '0'}
                  </Col>
                  <Col span={12} title={buildingInfo.isSingle}>
                    <span className='label'>整栋接管：</span>{buildingInfo.isSingle == 1 ? '是' : '否'}
                  </Col>
                </Row>
                /*: 
                <Row>
                  <Col span={12} title={buildingInfo.transferUnit}>
                    <span className={styles.label}>所属单位：</span>{buildingInfo.transferUnit ? buildingInfo.transferUnit : '-'}
                  </Col>
                  <Col span={12} title={buildingInfo.communityAddress}>
                    <span className={styles.label}>详细地址：</span>{buildingInfo.communityAddress ? buildingInfo.communityAddress : '-'}
                  </Col>
                  <Col span={12} title={buildingInfo.buildingNum}>
                    <span className={styles.label}>栋号：</span>{buildingInfo.buildingNum ? buildingInfo.buildingNum : '-'}
                  </Col>
                  <Col span={12} title={buildingInfo.buildingName2}>
                    <span className={styles.label}>建筑名称：</span>{buildingInfo.buildingName2 ? buildingInfo.buildingName2 : '-'}
                  </Col>
                  <Col span={12} title={buildingInfo.buildingArea}>
                    <span className={styles.label}>建筑面积（m²）：</span>{buildingInfo.buildingArea ? buildingInfo.buildingArea : '-'}
                  </Col>
                  <Col span={12} title={buildingInfo.buildingStructure}>
                    <span className={styles.label}>建筑结构：</span>{buildingInfo.buildingStructure ? buildingInfo.buildingStructure : '-'}
                  </Col>
                  <Col span={12} title={buildingInfo.basicBuildTerm}>
                    <span className={styles.label}>设计使用年限：</span>{buildingInfo.basicBuildTerm ? buildingInfo.basicBuildTerm : '-'}
                  </Col>
                  <Col span={12} title={buildingInfo.upFloor}>
                    <span className={styles.label}>地上层数：</span>{buildingInfo.upFloor ? buildingInfo.upFloor : '-'}
                  </Col>
                  <Col span={12} title={buildingInfo.downFloor}>
                    <span className={styles.label}>地下层数：</span>{buildingInfo.downFloor ? buildingInfo.downFloor : '-'}
                  </Col>
                  <Col span={12} title={buildingInfo.houseCount}>
                    <span className={styles.label}>房间数：</span>{buildingInfo.houseCount ? buildingInfo.houseCount : '-'}
                  </Col>
                  <Col span={12} title={buildingInfo.stateLive}>
                    <span className={styles.label}>自用总面积（m²）：</span>{buildingInfo.stateLive ? buildingInfo.stateLive : '-'}
                  </Col>
                  <Col span={12} title={buildingInfo.stateStoreLease}>
                    <span className={styles.label}>出租总面积（m²）：</span>{buildingInfo.stateStoreLease ? buildingInfo.stateStoreLease : '-'}
                  </Col>
                </Row>*/
              }
            </div>
          </Row>
          <div className='mainContainer'>
            <div className='contentHeader'>
              <div className="contentHeaderTitle">
                <p>房屋列表</p>
                <p>HOUSE LIST</p>
              </div>
            </div>
          </div>
          

          {/* buildingInfo.projectCode == 'PJ008' ?
            <div>
              <Row>
                <Table
                  bordered={true}
                  scroll={{ x: true }}
                  columns={columns}
                  dataSource={this.state.buildingData}
                  pagination={{
                    defaultPageSize: that.state.pageSize,
                    current: that.state.current,
                    onChange: that.pageChange,
                    total: that.state.total,
                    showTotal: total => `共 ${total} 项`
                  }}
                />
              </Row>
              <div className='mainContainer'>
                <div className='contentHeader'>
                  <div className="contentHeaderTitle">
                    <p>租赁信息</p>
                    <p>RENTAL INFORMATION</p>
                  </div>
                </div>
              </div>
              <Row>
                <Table
                  bordered={true}
                  scroll={{ x: true }}
                  columns={columns2}
                  dataSource={this.state.rentalData}
                  pagination={{
                    defaultPageSize: that.state._pageSize,
                    current: that.state._current,
                    onChange: that.pageChange2,
                    total: that.state._total,
                    showTotal: total => `共 ${total} 项`
                  }}
                />
              </Row>

              <div className='mainContainer'>
                <div className='contentHeader'>
                  <div className="contentHeaderTitle">
                    <p>能耗统计</p>
                    <p>ENERGY CONSUMPTION STATISTICS</p>
                  </div>
                </div>
              </div>
              <div className={styles.chart}>
                <ReactEcharts
                  option={this.state.chartData}
                  style={{
                    height: 455
                  }}
                />
              </div>
            </div>
            : */

            (Number(sessionStorage.getItem('isMap')) === 1 ?
              <div className={`${styles.w980} ${styles.h650}`}>
                <IframeComm
                  attributes={{
                    src: "/gis/mapBuilding.html",
                    style: {
                      width: '100%',
                      height: '100%',
                      top: '0px',
                      left: '0px',
                      position: "absolute"
                    }
                  }}
                  postMessageData={this.state.postMsg}
                />
                <div className={styles.buildingBox}>
                  <div className={styles.buildingBoxHeader}>{buildingInfo.buildingName === '' ? '暂未挂接' : buildingInfo.buildingName}</div>
                  {this.state.buildingData.length !== 0 ?
                    <div className={styles.maxHeight}>
                      {this.state.buildingData.map((item, index) => (
                        <div>
                          <Tooltip placement="left" title={item.houseName2}>
                            <Link
                              key={index}
                              className={styles.roomItem}
                              to={{
                                pathname: '/fe/assetMap/houseDetails',
                                state: {
                                  houseCode: item.houseCode
                                }
                              }}>
                              {item.houseName2}
                            </Link>
                          </Tooltip>
                        </div>
                      ))}
                    </div>
                    : null}
                </div>
              </div>
              :
              <div>
                {this.state.buildingData.length !== 0 ?
                  <div>
                    {this.state.buildingData.map((item, index) => (
                      <Tag color="magenta">
                        <Link
                          key={index}
                          to={{
                            pathname: '/fe/assetMap/houseDetails',
                            state: {
                              houseCode: item.houseCode
                            }
                          }}>
                          {item.houseName2}
                        </Link>
                      </Tag>
                    ))}
                  </div>
                  : null}
              </div>)
          }
            
  
          {
            /* buildingInfo.projectCode !== 'PJ008' ? */
            <div>
              <div className='mainContainer'>
                <div className='contentHeader'>
                  <div className="contentHeaderTitle">
                    <p>欠费情况</p>
                    <p>ARREARS</p>
                  </div>
                </div>
              </div>
              <div className={styles.fees}>
                {this.state.feesData.map((item, index) => {
                  return (
                    <div key={index} className={styles.feesItem}>
                      <p>
                        <Icon type={item.icon} theme="filled"></Icon>
                      </p>
                      <p>
                        {item.money}元
                      </p>
                      <p>
                        {item.title}
                      </p>
                    </div>
                  );
                })}
              </div>
            </div> /* : null */
          }
        </div>


        <Modal
          title="权属详情"
          centered
          visible={this.state.modalVisible}
          onOk={this.setModalVisible.bind(this, false)}
          onCancel={this.setModalVisible.bind(this, false)}
        >
          <Row className='mrb15'>
            <Col span={12}>证件类型：{this.state.step.doc.docType ? this.state.step.doc.docType : '-'}</Col>
            <Col span={12}>负责人：{this.state.step.itemList[0] ? this.state.step.itemList[0].userCode : '-'}</Col>
          </Row>
          <Steps direction="vertical" current={this.state.stepCount}>
            <Step title="无证" description={this.state.step.itemList[0] ? this.state.step.itemList[0].operateDate : ''} />
            <Step title="办理中" description={this.state.step.itemList[1] ? this.state.step.itemList[1].operateDate : ''} />
            <Step title="办理完成" description={this.state.step.itemList[2] ? this.state.step.itemList[2].operateDate : ''} />
            <Step title="过户中" description={this.state.step.itemList[3] ? this.state.step.itemList[3].operateDate : ''} />
            <Step title="有证" description={this.state.step.itemList[4] ? this.state.step.itemList[4].operateDate : ''} />
          </Steps>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default BuildingDetails;
